<template>
  <div class="userManagement">
    <a-flex justify="space-between">
      <h2>图片管理</h2>
      <a-space>
        <a-button type="primary" href="/picture/addPicture" target="_blank">新增图片</a-button>
        <a-button type="primary" href="/picture/batchAddPicture" target="_blank" ghost>批量创建图片</a-button>
      </a-space>
    </a-flex>
    <!-- 搜索框 -->
    <a-form layout="inline" :model="queryParams" @finish="doSearch" style="margin-bottom: 16px">
      <a-form-item label="名称或简介">
        <a-input v-model:value="queryParams.name" placeholder="请输入名称或简介" />
      </a-form-item>
      <a-form-item label="类型">
        <a-input v-model:value="queryParams.category" placeholder="请输入类型" />
      </a-form-item>
      <a-form-item label="标签">
        <a-select
          v-model:value="queryParams.tags"
          mode="tags"
          placeholder="请输入标签"
          allowClear
          style="width: 160px"
        ></a-select>
      </a-form-item>
      <a-form-item label="审批状态">
        <a-select
          v-model:value="queryParams.reviewStatus"
          placeholder="请选择审批状态"
          allowClear
          style="width: 160px"
          :options="PIC_REVIEW_STATUS_OPTIONS"
        ></a-select>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="margin-left: 16px">搜索</a-button>
      </a-form-item>
    </a-form>

    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doChange"
      :rowKey="(record) => record.id"
    >
      <template #bodyCell="{ column, record }">
        <!-- url特殊处理 -->
        <template v-if="column.dataIndex === 'url'">
          <a-image :src="record.url" :width="50"></a-image>
        </template>
        <!-- 标签特殊处理 -->
        <template v-else-if="column.dataIndex === 'tags'">
          <a-space wrap>
            <!-- 查看模式 -->
            <a-tag v-for="tag in JSON.parse(record.tags || '[]')" :key="tag">{{ tag }}</a-tag>
          </a-space>
        </template>
        <!--        图片信息特殊处理-->
        <template v-else-if="column.dataIndex === 'info'">
          <div>格式：{{ record.picFormat }}</div>
          <div>宽度：{{ record.picWidth }}</div>
          <div>高度：{{ record.picHeight }}</div>
          <div>大小：{{ (record.picSize / 1024).toFixed(2) }}kb</div>
        </template>
        <!--        审批信息特殊处理-->
        <template v-else-if="column.dataIndex === 'approveInfo'">
          <div>审批状态：{{ PIC_REVIEW_STATUS_MAP[record.reviewStatus] }}</div>
          <div>审批信息：{{ record.reviewMessage }}</div>
          <div>审批人：{{ record.reviewerId }}</div>
          <div v-if="record.reviewTime != null">
            审批时间：{{ dayjs(record.reviewTime).format('YYYY-MM-DD HH:mm:ss') }}
          </div>
        </template>
        <!-- 时间特殊处理-创建时间 -->
        <template v-else-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!-- 时间特殊处理-编辑时间 -->
        <template v-else-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <template v-else-if="column.key === 'action'">
          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              更多操作
              <DownOutlined />
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a-popconfirm
                    title="确认删除?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="deleteById(record.id)"
                    @cancel="cancel"
                  >
                    <a style="display: block; text-align: center;">删除</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item>
                  <a-button
                    type="link"
                    :href="`/picture/addPicture?id=${record.id}`"
                    target="_blank"
                    >编辑
                  </a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button
                    v-if="record.reviewStatus === 1 || record.reviewStatus === 0"
                    @click="userApprove(record.id, PIC_REVIEW_STATUS_ENUM.REJECT)"
                    >驳回
                  </a-button>
                </a-menu-item>
                <a-menu-item>
                  <a-button
                    v-if="record.reviewStatus === 2 || record.reviewStatus === 0"
                    @click="userApprove(record.id, PIC_REVIEW_STATUS_ENUM.PASS)"
                    >通过
                  </a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  adminApprovePictureUsingPost,
  adminPicPageUsingPost,
  deletePicByIdUsingPost,
} from '@/api/fileController.ts'
import { PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP, PIC_REVIEW_STATUS_OPTIONS } from '@/constants/picture.ts'
import { DownOutlined } from '@ant-design/icons-vue'

// 定义表格数据
const dataList = ref<API.Picture[]>([])
// 定义总条数
const total = ref(0)
// 定义查询参数,默认1页10条
const queryParams = reactive<API.PictureQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'editTime',
  sortOrder: 'descend',
  name: '',
  category: '',
  tags: [],
})

// 定义分页对象
const pagination = computed(() => {
  return {
    current: queryParams.current,
    pageSize: queryParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共${total}条`,
  }
})

// 从后端分页查询数据
async function getPageData() {
  const resp = await adminPicPageUsingPost({ ...queryParams })
  if (resp.data.code === 0 && resp.data.data) {
    dataList.value = resp.data.data.records ?? []
    total.value = resp.data.data.total ?? 0
  } else {
    message.error('查询用户数据失败,' + resp.data.message)
  }
}

// 表格分页变化
function doChange(record: any) {
  queryParams.current = record.current
  queryParams.pageSize = record.pageSize
  getPageData()
}

// 搜索
function doSearch() {
  queryParams.current = 1
  getPageData()
}

// 删除
async function deleteById(id: string) {
  const resp = await deletePicByIdUsingPost({ id })
  if (resp.data.code === 0) {
    message.success('删除成功')
    getPageData()
  } else {
    message.error('删除失败,' + resp.data.message)
  }
}

/**
 * 管理员审批
 * @param id
 * @param status
 */
async function userApprove(id: number, status: number) {
  const resp = await adminApprovePictureUsingPost({
    id: id,
    reviewStatus: status,
    reviewMessage: status === 1 ? '管理员审批通过' : '管理员审批驳回',
  })
  if (resp.data.code === 0) {
    message.success('执行成功')
    getPageData()
  } else {
    message.error('执行失败,' + resp.data.message)
  }
}

const cancel = (e: MouseEvent) => {
  message.error('取消');
};

// 页面加载时获取数据
onMounted(() => {
  getPageData()
})

// 表格列定义
const columns = [
  {
    title: 'id',
    dataIndex: 'id',
  },
  {
    title: '图片',
    dataIndex: 'url',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '简介',
    dataIndex: 'introduction',
  },
  {
    title: '类型',
    dataIndex: 'category',
  },
  {
    title: '标签',
    dataIndex: 'tags',
  },
  {
    title: '图片信息',
    dataIndex: 'info',
  },
  {
    title: '审批信息',
    dataIndex: 'approveInfo',
  },
  {
    title: '用户id',
    dataIndex: 'userId',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]
</script>

<style scoped>
/* 可以添加一些编辑状态的样式 */
:deep(.ant-table-cell) {
  transition: background-color 0.2s;
}

:deep(.ant-table-cell:hover) {
  background-color: #f5f5f5;
}
</style>
